package fr.coding.kata.nantes.bowling.michel;

import fr.coding.kata.nantes.bowling.commons.BowlingInterface;

import java.util.ArrayList;
import java.util.List;

public class Bowling implements BowlingInterface {

    private final List<Roll> rolls = new ArrayList<Roll>();

    @Override
    public Integer call() throws Exception {
        int total = 0;
        int currentFrame = 1;
        boolean secondThrowInFrame = false;
        for (final Roll roll : rolls) {
            if (currentFrame < 10) {
                total += roll.calculateScore();
            } else {
                total += roll.getValue();
            }
            if (roll.isStrike() || secondThrowInFrame) {
                currentFrame++;
                secondThrowInFrame = false;
            } else {
                secondThrowInFrame = true;
            }
        }
        return total;
    }

    @Override
    public BowlingInterface with(final String rollsString) {
        Roll previous = Roll.newInstance('0'); // value of 0, better than null.
        rolls.clear();

        for (final char c : rollsString.toCharArray()) {
            final Roll roll = Roll.newInstance(c);
            roll.setPrevious(previous);
            rolls.add(roll);
            previous.setNext(roll);
            previous = roll;
        }
        return this;
    }

}
